<!-- 引入必要的依赖 -->
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>传感器数据与日志</title>
    <!-- 使用bootcss镜像源 -->
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet">
    <!-- <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"> -->
    <style>
        /* 设置页面高度和背景图片 */
        body, html {
            height: 100%;
            margin: 0;
            font-family: Arial, Helvetica, sans-serif;
            background-image: url('{{ url_for("static", filename="image.jpg") }}');
            background-size: cover;
            background-position: center;
            background-repeat: no-repeat;
        }

        /* 主容器 */
        .container-fluid {
            height: 100%;
            padding: 20px;
        }

        /* 主行 */
        .row {
            height: 100%;
        }
        /* .col-md-3 {
            flex: 0 0 35%;
            max-width: 28%;
        } */
        /* 日志框样式 */
        .log-box {
            background-color: rgba(255, 255, 255, 0.9);
            padding: 15px;
            border-radius: 8px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            /* height: 100%; */
            height: 470px;
            overflow-y: auto;
        }

        /* 中间容器样式 */
        .middle-container {
            background-color: rgba(255, 255, 255, 0.9);
            padding: 15px;
            border-radius: 8px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            height: 100%;
            overflow-y: auto;
            text-align: center;
        }

        /* 传感器数据容器 */
        .sensor-data {
            background-color: rgba(255, 255, 255, 0.9);
            padding: 15px;
            border-radius: 8px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            height: 95%;
            overflow-y: auto;
        }

        /* 响应式调整 */
        @media (max-width: 768px) {
            .log-box, .middle-container, .sensor-data {
                height: auto;
                margin-bottom: 20px;
            }
        }

        .chartjs-render-monitor {
            transition: opacity 0.3s; /* 添加淡入淡出效果 */
        }
        
        /* 高亮激活的坐标轴标签 */
        .chartjs-grid text {
            filter: drop-shadow(0 0 2px white);
        }

        .loss-chart-container {
            background-color: rgba(255, 255, 255, 0.9);
            padding: 15px;
            border-radius: 8px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            margin-top: 15px;
        }
        
        #lossChart {
            width: 100%!important;
            height: 250px!important;
        }
    </style>
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script>
        $(document).ready(function(){
            // 定义一个函数来获取最新的日志并更新表格
            function updateLogs() {
                $.ajax({
                    url: "{{ url_for('get_latest_logs') }}",
                    method: 'GET',
                    success: function(data) {
                        // 清空现有的日志
                        $('#logTable tbody').empty();
                        // 遍历返回的数据并添加到表格中
                        data.forEach(function(log){
                            var row = '<tr>' +
                                '<td>' + log.Time + '</td>' +
                                '<td>' + log.State + '</td>' +
                              '</tr>';
                            $('#logTable tbody').append(row);
                        });
                    },
                    error: function(xhr) {
                        console.log("获取日志失败: ", xhr.statusText);
                    }
                });
            }

            // 初始调用一次
            updateLogs();

            // 每5秒调用一次
            setInterval(updateLogs, 5000);
            
            // 创建损失图表实例
            let lossChart = null;
            
            function updateLossChart() {
                $.ajax({
                    url: "/attack",
                    method: 'GET',
                    success: function(data) {
                        if (data.status === "success" && data.data) {
                            const losses = data.data;
                            
                            // 生成时间标签（示例使用序号）
                            const labels = losses.map((_, index) => index + 1);
                            
                            // 首次初始化图表
                            if (!lossChart) {
                                const ctx = document.getElementById('lossChart').getContext('2d');
                                lossChart = new Chart(ctx, {
                                    type: 'line',
                                    data: {
                                        labels: labels,
                                        datasets: [{
                                            label: 'Anomaly Score',
                                            data: losses,
                                            borderColor: 'rgba(255, 0, 0, 0.8)',
                                            backgroundColor: 'rgba(255, 0, 0, 0.1)',
                                            fill: true,
                                            lineTension: 0.1,
                                            pointRadius: 2
                                        }]
                                    },
                                    options: {
                                        responsive: true,
                                        maintainAspectRatio: false,
                                        animation: {
                                            duration: 0
                                        },
                                        scales: {
                                            x: {
                                                title: {
                                                    display: true,
                                                    text: ''
                                                }
                                            },
                                            y: {
                                                title: {
                                                    display: true,
                                                    text: '异常分数'
                                                },
                                                beginAtZero: true,
                                                max: 2, // 固定最大值为2
                                            }
                                        }
                                    }
                                });
                            } else {
                                // 更新现有图表数据
                                lossChart.data.labels = labels;
                                lossChart.data.datasets[0].data = losses;
                                lossChart.update();
                            }
                        }
                    },
                    error: function(xhr) {
                        console.error("获取损失数据失败:", xhr.statusText);
                    }
                });
            }
            
            // 初始调用并设置定时更新
            updateLossChart();
            setInterval(updateLossChart, 3000);
            // 初始化选中的传感器变量
            var selectedSensor = null;
        
            // 绑定change事件到下拉框
            $('#sensorSelect').on('change', function() {
                // 获取当前选中的传感器值
                selectedSensor = $(this).val();
                console.log("当前选中的传感器:", selectedSensor);
        
                // 如果选择了有效的传感器，则发送到后端
                if (selectedSensor) {
                    addSelectedSensorToBackend();
                } else {
                    // 如果未选择任何传感器，可以选择清空后端的数据或不做处理
                    console.log("未选择任何传感器。");
                }
            });
            
            // 定义一个函数来发送数据到后端
            function addSelectedSensorToBackend() {
                $.ajax({
                    url: "/add_selected_sensors", // 替换为您的后端接口URL
                    method: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify({ sensor: selectedSensor }),
                    success: function(response) {
                        console.log("数据成功发送到后端:", response);
                        // 根据需要处理后端返回的数据
                        // // 重新渲染图表
                        renderSensorGraphs();
                    },
                    error: function(xhr) {
                        console.error("发送数据失败:", xhr.statusText);
                        // 根据需要处理错误情况
                    }
                });
            }

            function renderSensorGraphs() {
                console.log('开始绘制图表');
                $.ajax({
                    url: "{{ url_for('get_sensor_data') }}",
                    method: 'GET',
                    success: function(data) {
                        // 清空之前的图表容器
                        $('.sensor-graphs').empty();
                        
                        // 获取容器宽度，计算每个图表应有的宽度
                        // let containerWidth = $('.sensor-graphs').width();
                        // let numCharts = Object.keys(data).length;
                        // let chartWidth = containerWidth / numCharts - 30; // 减去一些间距
                        let chartWidth = 600; // 固定宽度为600像素
                        let spacing = 10; // 设置间距为10像素

                        // 遍历每个传感器的数据
                        for(var sensor in data){
                            if(data.hasOwnProperty(sensor)){
                                var sensorData = data[sensor];
                                var labels = sensorData.map(function(entry) {
                                    return entry.Time;
                                });
                                var dataPoints = sensorData.map(function(entry) {
                                    return entry.Data;
                                });
                                
                                // 创建唯一的canvas id
                                var canvasId = 'chart-' + sensor + '-canvas';
                                var buttonId = 'delete-' + sensor + '-btn';
                                var buttonId2 = 'big-' + sensor + '-btn';
                                var buttonId3 = 'small-' + sensor + '-btn';
                                var canvasHtml = `
                                    <div style="flex: 0 0 ${chartWidth}px; max-width: ${chartWidth}px; padding: 0;">
                                        <div style="display: flex; 
                                                    justify-content: space-between; 
                                                    align-items: center;
                                                    margin-bottom: 10px;
                                                    padding: 0 8px;">
                                            <h5 style="margin: 0;">${sensor}</h5>
                                            <button type="button"
                                                    id="${buttonId2}"  
                                                    class="big-sensor-btn" 
                                                    data-sensor="${sensor}"
                                                    style="margin-left: 10px;">
                                                ■
                                            </button>
                                            <button type="button"
                                                    id="${buttonId3}"  
                                                    class="small-sensor-btn" 
                                                    data-sensor="${sensor}"
                                                    style="margin-left: 10px;">
                                                -
                                            </button>
                                            <button type="button"
                                                    id="${buttonId}"  
                                                    class="delete-sensor-btn" 
                                                    data-sensor="${sensor}"
                                                    style="margin-left: 10px;">
                                                X
                                            </button>
                                        </div>
                                        <canvas id="${canvasId}" 
                                                width="${chartWidth}" 
                                                height="250"
                                                style="display: block; width: 100%!important;"></canvas>
                                    </div>
                                `;
                                $('.sensor-graphs').append(canvasHtml);
                                
                                // 绘制图表
                                var ctx = document.getElementById(canvasId).getContext('2d');
                                var chart = new Chart(ctx, {
                                    type: 'line',
                                    data: {
                                        labels: labels,
                                        datasets: [{
                                            label: sensor,
                                            data: dataPoints,
                                            borderColor: 'black',
                                            backgroundColor: 'rgba(0, 0, 0, 0.1)',
                                            fill: true,
                                            lineTension: 0.1
                                        }]
                                    },
                                    options: {
                                        legend: {
                                            display: false // 隐藏图例
                                        },
                                        pointBackgroundColor: 'transparent',
                                        pointBorderColor: 'transparent',
                                        responsive: true,
                                        maintainAspectRatio: true,
                                        animation: {
                                            duration: 0 // 禁用动画
                                        },
                                        scales: {
                                            xAxes: [{
                                                type: 'time',
                                                time: {
                                                    unit: 'second', // 将时间单位改为秒
                                                    displayFormats: {
                                                        second: 'ss' // 设置时间显示格式为秒
                                                    }
                                                },
                                                ticks: {
                                                    maxTicksLimit: 10
                                                }
                                            }],
                                            yAxes: [{
                                                ticks: {
                                                    beginAtZero: true
                                                }
                                            }]
                                        }
                                    }
                                });
                                
                                // 检查图表是否成功绘制
                                if (chart instanceof Chart) {
                                    console.log('图表绘制成功:', chart);
                                } else {
                                    console.error('图表绘制失败');
                                }
                            }
                        }
                    },
                    error: function(xhr) {
                        console.log("获取传感器数据失败: ", xhr.statusText);
                    }
                });
            }

            // 初始渲染图表
            renderSensorGraphs();
            setInterval(renderSensorGraphs, 1000);

            function renderBigSensorGraphs() {
                console.log('开始绘制图表');
                $.ajax({
                    url: "{{ url_for('get_big_sensor_data') }}",
                    method: 'GET',
                    success: function(data) {
                        $('.big-sensor-graphs').empty();
                        
                        // 创建唯一canvas容器
                        const canvasHtml = `
                            <div style="position: relative; height:600px; width:600px">
                                <canvas id="combined-chart-canvas" width = 630 height=660></canvas>
                            </div>`;
                        $('.big-sensor-graphs').append(canvasHtml);
            
                        const ctx = document.getElementById('combined-chart-canvas').getContext('2d');
                        const allYAxes = []; // 存储所有Y轴配置
                        let activeYAxisIndex = -1; // 当前激活的Y轴索引
            
                        // 生成数据集和对应Y轴配置
                        const datasets = Object.keys(data).map((sensor, index) => {
                            // 为每个传感器创建独立的Y轴
                            const yAxisID = `y-axis-${index}`;
                            const color = generateColorFromString(sensor);
                            
                            allYAxes.push({
                                id: yAxisID,
                                type: 'linear',
                                display: false, // 默认隐藏坐标轴
                                position: 'left',
                                gridLines: {
                                    drawOnChartArea: false,
                                    color: color + '33' // 添加透明度
                                },
                                ticks: {
                                    beginAtZero: false,
                                    fontColor: color,
                                    display: false
                                },
                                z: 10 - index // 初始层级
                            });
            
                            return {
                                label: sensor,
                                data: data[sensor].map(entry => entry.Data),
                                yAxisID: yAxisID,
                                borderColor: color + '99', // 半透明颜色
                                backgroundColor: 'transparent',
                                fill: false,
                                lineTension: 0.1,
                                pointRadius: 0,
                                borderWidth: 3,
                                hidden: false
                            };
                        });
            
                        const chart = new Chart(ctx, {
                            type: 'line',
                            data: {
                                labels: data[Object.keys(data)[0]].map(entry => entry.Time),
                                datasets: datasets
                            },
                            options: {
                                responsive: false,
                                maintainAspectRatio: false,
                                animation: { duration: 0 },
                                hover: { mode: 'nearest' },
                                tooltips: { mode: 'nearest' },
                                scales: {
                                    xAxes: [{
                                        type: 'time',
                                        time: {
                                            unit: 'second',
                                            displayFormats: { second: 'ss' }
                                        }
                                    }],
                                    yAxes: allYAxes
                                },
                                onClick: (e, elements) => {
                                    if (elements.length > 0) {
                                        const datasetIndex = elements[0]._datasetIndex;
                                        
                                        // 更新所有坐标轴层级
                                        allYAxes.forEach((axis, index) => {
                                            axis.z = (index === datasetIndex) ? 100 : 10 - index;
                                            axis.display = (index === datasetIndex);
                                            axis.gridLines.drawOnChartArea = (index === datasetIndex);
                                            axis.ticks.display = (index === datasetIndex);
                                        });
            
                                        // 更新数据集透明度
                                        chart.data.datasets.forEach((ds, index) => {
                                            ds.borderColor = generateColorFromString(ds.label) + 
                                                (index === datasetIndex ? 'FF' : '33');
                                        });
            
                                        chart.update();
                                    }
                                }
                            }
                        });
            
                        // 初始化激活第一个坐标轴
                        allYAxes[0].display = true;
                        allYAxes[0].gridLines.drawOnChartArea = true;
                        allYAxes[0].ticks.display = true;
                        chart.update();
                    }
                });
            }

            // 初始渲染图表
            renderBigSensorGraphs();
            setInterval(renderBigSensorGraphs, 1000);

            function getRandomColor() {
                // 生成随机十六进制颜色（例如 #FF5733）
                return '#' + Math.floor(Math.random()*16777215).toString(16);
            }

            // 辅助函数：根据字符串生成伪随机颜色
            function generateColorFromString(str) {
                let hash = 0;
                for (let i = 0; i < str.length; i++) {
                    hash = str.charCodeAt(i) + ((hash << 5) - hash);
                }
                const color = (hash & 0x00FFFFFF).toString(16).toUpperCase();
                return '#' + ('00000' + color).slice(-6);
            }

            // 辅助函数：将十六进制颜色转换为RGB数组
            function hexToRgb(hex) {
                var bigint = parseInt(hex.slice(1), 16);
                var r = (bigint >> 16) & 255;
                var g = (bigint >> 8) & 255;
                var b = bigint & 255;
                return [r, g, b];
            }
                    
            // 添加删除按钮的事件监听器，注意这部分一定要放在后面，因为得等按钮渲染完了才可以
            $(document).on('click', '.delete-sensor-btn', function() {
                var sensor = $(this).data('sensor');
                console.log('删除传感器:', sensor);
                $.ajax({
                    url: "/delete_selected_sensors", // 后端新增的路由
                    method: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify({ sensor: sensor }),
                    success: function(response) {
                        console.log("传感器已删除:", response);
                        // // 重新渲染图表
                        renderSensorGraphs();
                        // deleteSelectedSensorToBackend();
                    },
                    error: function(xhr) {
                        console.error("删除传感器失败:", xhr.statusText);
                    }
                });
            });
            $(document).on('click', '.big-sensor-btn', function() {
                var sensor = $(this).data('sensor');
                console.log('放大传感器:', sensor);
                $.ajax({
                    url: "/big_selected_sensors", // 后端新增的路由
                    method: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify({ sensor: sensor }),
                    success: function(response) {
                        console.log("传感器已放大:", response);
                        // // 重新渲染图表
                        // renderSensorGraphs();
                    },
                    error: function(xhr) {
                        console.error("放大传感器失败:", xhr.statusText);
                    }
                });
            });
            $(document).on('click', '.small-sensor-btn', function() {
                var sensor = $(this).data('sensor');
                console.log('缩小传感器:', sensor);
                $.ajax({
                    url: "/small_selected_sensors", // 后端新增的路由
                    method: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify({ sensor: sensor }),
                    success: function(response) {
                        console.log("传感器已缩小:", response);
                        // // 重新渲染图表
                        // renderSensorGraphs();
                    },
                    error: function(xhr) {
                        console.error("缩小传感器失败:", xhr.statusText);
                    }
                });
            });
        });
    </script>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- 左侧日志框 -->
            <div class="col-md-3">
                <div class="log-box">
                    <h4>日志</h4>
                    <hr>
                    <table id="logTable" class="table table-bordered">
                        <thead>
                            <tr>
                                <th>时间</th>
                                <th>状态</th>
                            </tr>
                        </thead>
                        <tbody>
                            {% if logs %}
                                {% for log in logs %}
                                    <tr>
                                        <td>{{ log.Time }}</td>
                                        <td>{{ log.State }}</td>
                                    </tr>
                                {% endfor %}
                            {% else %}
                                <tr><td colspan="2">暂无日志数据。</td></tr>
                            {% endif %}
                        </tbody>
                    </table>
                </div>
                <div class="loss-chart-container mt-3">
                    <h5>异常曲线</h5>
                    <canvas id="lossChart"></canvas>
                </div>
            </div>

            <!-- 中间容器 -->
            <div class="col-md-6 middle-container">
                <h4>异常监测</h4>
                <p style="color: #ff0000; ">状态异常，请及时处理</p>
                 <!-- <p style="color: #00ff00; ">状态正常</p> -->
                <!-- 显示已选传感器列表 -->
                <div class="sensor-data">
                    <div class="big-sensor-graphs">
                        <!-- 折线图将动态插入到这里 -->
                    </div>
                </div>
            </div>

            <!-- 右侧传感器数据 -->
            <div class="col-md-3">
                <!-- 下拉框-->
                <div class="dropdown-container">
                    <select class="form-control" id="sensorSelect" name="sensor_name">
                        {% for sensor in sensors %}
                            <option value="{{ sensor }}">{{ sensor }}</option>
                        {% endfor %}
                    </select>
                </div>
                <!-- 显示已选传感器列表 -->
                <div class="sensor-data">
                    <h4>传感器数据</h4>
                    <hr>
                    <div class="sensor-graphs">
                        <!-- 折线图将动态插入到这里 -->
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>